// Copyright (c) 2020 Presto Labs Pte. Ltd.
// Author: leon

#pragma once

#include <memory>
#include <optional>
#include <string>
#include <string_view>
#include <vector>

#include "coin2/exchange/base/symbology/spot_product.h"
#include "coin2/exchange/base/symbology/util.h"
#include "coin2/exchange/bitstamp/symbology/currency.h"

namespace coin2::exchange::bitstamp::symbology {

class BitstampProduct : public base::symbology::SpotProduct<BitstampCurrency, BitstampProduct>,
                    public base::symbology::ProductFromStrMixin<BitstampProduct> {
 public:
  using BaseProduct = SpotProduct<BitstampCurrency, BitstampProduct>;

  BitstampProduct(const BitstampCurrency& base, const BitstampCurrency& quote)
      : SpotProduct(
            base,
            quote,
            ToBitstampNativeProduct(base, quote),
            ToBitstampNativeProduct(base, quote),
            base::market::ExchangeType::Bitstamp) {}

  static std::unique_ptr<BitstampProduct> FromNativeStrImpl(
      const std::string& native_product,
      int64_t resolve_timestamp) {
    std::unique_ptr<BitstampCurrency> base_ptr;
    std::unique_ptr<BitstampCurrency> quote_ptr;
    bool success = ParseBitstampNativeProduct(
        native_product, resolve_timestamp, &base_ptr, &quote_ptr);
    if (success) {
      return std::make_unique<BitstampProduct>(*base_ptr, *quote_ptr);
    } else {
      return {};
    }
  }

 private:
  static bool ParseBitstampNativeProduct(
      std::string product_str,
      int64_t resolve_timestamp,
      std::unique_ptr<BitstampCurrency>* base_ptr,
      std::unique_ptr<BitstampCurrency>* quote_ptr) {
    using base::market::MarketType;
    using base::symbology::HasValue;

    std::string base;
    std::string quote;

    static const std::string quotes[] = {"btc", "eth", "eur", "gbp", "pax", "usd", "usdc", "usdt"};
    for (const auto& quote_cand : quotes) {
      if (StringEndsWith(product_str, quote_cand)) {
        size_t base_len = product_str.size() - quote_cand.size();
        std::string base = product_str.substr(0, base_len);
        *base_ptr = BitstampCurrency::FromNativeStrNoThrow(base, resolve_timestamp);
        *quote_ptr = BitstampCurrency::FromNativeStrNoThrow(quote_cand, resolve_timestamp);
        return true;
      }
    }
    return false;
  }

  static std::string ToBitstampNativeProduct(
      const BitstampCurrency& base, const BitstampCurrency& quote) {
    using base::market::MarketType;

    std::stringstream ss;
    ss << base.native_currency(MarketType::Spot) << quote.native_currency(MarketType::Spot);
    return ss.str();
  }
};

}  // namespace coin2::exchange::bitstamp::symbology
